import json

from flask import Flask, jsonify, request, Response
from flask_cors import CORS
from mysql_data.mysql_con import MysqlHandle

app = Flask(__name__)
CORS(app, supports_credentials=True)


"""
    查询接收方和发送方最新的10个id
    :param flag:区分发送方接收方(1:发送方 2:接收方)
"""


@app.route('/get_newIds')
def get_newid_list():
    flag = request.args.get("flag", " ")
    if flag:
        datas = MysqlHandle().get_ids_data(int(flag))
        if datas:
            return json.dumps({"code": 200, "msg": "access succee", "data": datas})
        return json.dumps({"code": 500, "msg": "mysql err not data"})
    return json.dumps({"code": 400, "msg": "param not empty"})


"""
    查询接收方和发送方的流速
    :param id: 客户端id
    :param flag:区分发送方接收方(1:发送方 2:接收方)
    :param start_time:查询范围开始时间戳
    :param end_time:  查询范围结束结束时间戳
    :return: 发送方接收方 流量流速数据
"""


@app.route('/get_speed')
def get_speed_data():
    id = request.args.get("id", " ")
    flag = request.args.get("flag", " ")
    start_time = request.args.get("start_time", " ")
    end_time = request.args.get("end_time", " ")
    if id and flag and start_time and end_time:
        id, flag, start_time, end_time = int(id), int(flag), int(start_time), int(end_time)
        datas = MysqlHandle().get_speed(id, flag, start_time, end_time)
        if datas:
            return json.dumps({"code": 200, "msg": "access succee", "data": datas})
        return json.dumps({"code": 500, "msg": "mysql err not data"})
    return json.dumps({"code": 400, "msg": "param not empty"})

"""
    查询接收方和发送方流量最新数据20个
    :param flag:区分发送方接收方(1:发送方 2:接收方)
"""
@app.route('/get_traffic')
def get_traffic_data():
    flag = request.args.get("flag", " ")
    if flag:
        datas = MysqlHandle().get_traffic(int(flag))
        if datas:
            return json.dumps({"code": 200, "msg": "access succee", "data": datas})
        return json.dumps({"code": 500, "msg": "mysql err not data"})
    return json.dumps({"code": 400, "msg": "param not empty"})



"""
    查询接收方和发送方实时最新数据20个
    :param flag:区分发送方接收方(1:发送方 2:接收方)
"""
@app.route('/get_real_time')
def get_real_time():
    flag = request.args.get("flag", " ")
    if flag:
        datas = MysqlHandle().get_retime_data(int(flag))
        if datas:
            return json.dumps({"code": 200, "msg": "access succee", "data": datas})
        return json.dumps({"code": 500, "msg": "mysql err not data"})
    return json.dumps({"code": 400, "msg": "param not empty"})

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)
